const { Server } = require('socket.io');
const user = {};

module.exports = function (serve) {
  const io = new Server(serve, { cors: true });

  io.on('connection', (socket) => {
    socket.send('链接成功！');

    socket.on('disconnect', () => {
      console.log('user disconnected');
    });

    socket.on('login', (data) => {
      user[data.userID] = socket.id;
    });

    socket.on('logout', (data) => {
      if (user[data.userID]) {
        delete user[data.userID];
      }
    });

    socket.on('message', (data) => {
      const { to, payload } = data;
      if (user[to]) {
        const current = io.sockets.sockets.get(user[to]);
        current && current.send(payload.text);
      }
    });
  });
};
